import React, { PureComponent } from 'react';
import Form from '@wanhu/antd-legacy/lib/form';
import { Button, Modal, Table } from 'antd';
import message from '@wanhu/antd-legacy/lib/message'
import memoize from 'memoize-one';
import {
    patientInfo, func, number,
} from '@wanhu/business/lib/health-record/prop-types';
import './index.less';
import NewTable from './newTable/tableContent';
import api from '../../../../../../api/api';

import HasPermission, { testPermission } from '../../../../../common/HasPermission';
// import TableName from './table/tableName';
// import TableContent from './table/tableContent';

const FormItem = Form.Item;

const buttonStyle = {
    display: 'block',
    width: '100%',
};


export default class HealthCheckRecordsEdit extends PureComponent {
    constructor (props) {
        super(props)
        this.state = {
            visible:false,
            tableMainData:{},
            detailData:{},
            patientId: '',
            dataSource: null,
            getDetailData: null,
            columns:[{
                title: '建档日期',
                dataIndex: 'physicalExaminationDate',
                key: 'physicalExaminationDate',
            }, {
                title: '业务来源',
                dataIndex: 'businessSource',
                key: 'businessSource',
            }, {
                title: '系统来源',
                dataIndex: 'source',
                key: 'source',
            }, {
                title: '录入人',
                dataIndex: 'createUserName',
                key: 'createUserName',
            }, {
                title: '录入时间',
                dataIndex: 'createDate',
                key: 'createDate',
            }, {
                title: '详情',
                dataIndex: 'detail',
                key: 'detail',
                render: (text, record) => (
                    <span>
                        <a onClick={() => this.lookDetails(record)} style={{textDecoration:'underline',display:'inlinieBlock',marginRight:'10px'}}>
                        查看
                        </a>
                        { testPermission('call:patient:physicalExamination:edit')?<a onClick={() => this.lookDetails(record, 'editPower')} style={{textDecoration:'underline'}}>
                        编辑
                        </a>:null}
                    </span>
                )
            }],
            pageIndex: 1,
            pageSize: 10,
            pageTotal: null,
            isSaveNeedInit: false,
            editPower:false
        }
    }
    static propTypes = {
        patientInfo: patientInfo.isRequired,
        addHealthCheckRecord: func.isRequired,
        setHealthCheckRecordFields: func.isRequired,
        scrollXPadding: number,
    }

    static defaultProps = {
        scrollXPadding: 0,
    }

    async componentDidMount() {
        // const main = await api.getPatientHealthCheckRecordsNew(this.props.patientId)
        this.getListData()
    }
    async getListData() {
        const self = this
        this.setState({
            pageIndex: 1,
            pageTotal: null
        })
        const { list } = await api.getPhysicalRecordListNew(this.props.patientId, 0, this.state.pageSize+1);
        if (list.length === this.state.pageSize + 1) {
            this.setState({
                pageTotal: list.length
            })
        }
        this.setState({
            dataSource:list.slice(0,self.state.pageSize),
            patientId:this.props.patientId
        })
        console.log(this.state.dataSource)
    }
    initMainData = async (value) => {
        if (value) {
            this.setState({
                isSaveNeedInit:true
            })
        } else {
            this.setState({
                visible:false,
            })
        }

        // this.getListData();
    }

    componentDidUpdate() {
    }

    componentWillUnmount() {
        if (this.setFieldsTimeout) {
            clearTimeout(this.setFieldsTimeout);
        }
    }
    async lookDetails(value, editPower) {
        let main = await api.getPhysicalRecordListNewDetail(this.state.patientId, value.id);
        // 饮食口味格式化处理 start
        let dietaryHabitData = Number(main.dietaryHabit)
        let dietaryHabitItem = []
        if(dietaryHabitData && dietaryHabitData>0){
            if((dietaryHabitData & 1)>0){
                dietaryHabitItem.push(1)
            }
            if((dietaryHabitData & 2)>0){
                dietaryHabitItem.push(2)
            }
            if((dietaryHabitData & 4)>0){
                dietaryHabitItem.push(4)
            }
            if((dietaryHabitData & 8)>0){
                dietaryHabitItem.push(8)
            }
        }
        main.dietaryHabit = dietaryHabitItem
        // 饮食口味格式化处理 end
        this.setState({
            visible: true,
            isSaveNeedInit: false,
            getDetailData: main,
            editPower: editPower?true:false
        },()=>{
            console.log('ok')
        })
    }


    setFieldsDelayBatched(id, tmpid, fields) {
        if (!this.pendingSetFields) {
            this.pendingSetFields = [];
        }
        this.pendingSetFields.push([id, tmpid, fields]);
        if (this.setFieldsTimeout) {
            clearTimeout(this.setFieldsTimeout);
        }
        this.setFieldsTimeout = setTimeout(() => {
            const { setHealthCheckRecordFields } = this.props;
            const { pendingSetFields } = this;
            this.pendingSetFields = null;
            this.setFieldsTimeout = null;

            if (pendingSetFields.length === 1) {
                const [id, tmpid, fields] = pendingSetFields[0];
                setHealthCheckRecordFields({
                    ...fields,
                    id,
                    tmpid,
                });
                return;
            }
            const batchedUpdates = [];
            pendingSetFields.forEach(([id, tmpid, fields]) => {
                let update = batchedUpdates.find(
                    u => (id && id === u.id) || (tmpid && tmpid === u.tmpid),
                );
                if (!update) {
                    update = { id, tmpid };
                    batchedUpdates.push(update);
                }
                Object.assign(update, fields);
            });
            setHealthCheckRecordFields(batchedUpdates);
        });
    }

    getPopupContainer = () => this.popupContainer;

    setScrollXPosition(x, parentSticky) {
        if (parentSticky) {
            if (this.scrollTranslateElement) {
                this.scrollTranslateElement.style.transform = `translateX(${-x}px)`;
            }
            if (this.scrollPlaceholder) {
                this.scrollPlaceholder.style.transform = `translateX(${-x}px)`;
            }
        } else {
            if (this.scrollStickyElement) {
                this.scrollStickyElement.style.transform = `translateX(${x}px)`;
            }
            if (this.scrollTranslateElement) {
                this.scrollTranslateElement.style.transform = `translateX(${-x}px)`;
            }
        }
    }

    addRecord(fields) {
        const { addHealthCheckRecord } = this.props;
        const randId = `temp:${Date.now().toString(36).substr(-4)}${Math.random().toString(36).substr(-4)}`;
        addHealthCheckRecord({ ...fields, tmpid: randId });
    }
      handleOk = (e) => {
        this.setState({
          visible: false,
          detailDataInit:{}
        });
      }
    handleCancel = (e) => {
        this.setState({
          visible: false,
          detailDataInit:{}
        });
        if (this.state.isSaveNeedInit) {
            this.getListData()
        }
      }
      PGtable(){
        const data = this.state.tableMainData
        return(
            <div className="PGtableStyle">
                {/* <table className="">
                    <thead>
                        <tr>
                            <td>评估日期</td>
                            <td>数据来源</td>
                            <td style={{width:'100px'}}>操作</td>
                        </tr>
                    </thead>
                    <tbody>
                        {data.map((item,index)=>{
                            return (
                                <tr>
                                    <td>{item.physicalExaminationDate}</td>
                                    <td>{ item.updateBy }</td>
                                    <td><span className="edit" onClick={()=>this.lookPGForm(item)}>查看</span></td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table> */}
                {/* <Table dataSource={this.state.dataSource} columns={columns} /> */}
            </div>
        )
      }
    lookPGForm(item){
        this.setState({
            detailData:item,
            visible:false,
            detailDataInit:{}
        },()=>{
            this.setState({
                visible: true,
                isSaveNeedInit: false,
                detailDataInit:this.state.detailData
            })
        })
    }
    addRecordClickListener = (item) => {
        this.setState({
            visible:false,
        },()=>{
            this.setState({
                visible: true,
                isSaveNeedInit: false,
                getDetailData: {}
            })
        })
    }
    tableChange = async (pagination) => {
        const self = this
        console.log(pagination)
        const { pageIndex } = this.state
        const { pageSize,current } = pagination
        const skip = (current-1)*pageSize;
        const limit = skip + pageSize;
        this.setState({
            pageIndex: current,
            pageSize: pageSize
        })
        const { list } = await api.getPhysicalRecordListNew(this.props.patientId, skip, pageSize+1);
        if (list.length === pageSize+1 && pageIndex === pagination.current -1) {
            this.setState({
                pageTotal:this.state.pageTotal+pageSize
            })
        }
        this.setState({
            dataSource: list.slice(0,self.state.pageSize),
            pageIndex:pagination.current
        })
    };
    render() {
        const { patientInfo, patientId } = this.props;
        const { dataSource,columns,pageIndex,pageSize,pageTotal } = this.state;
        // const columns = this.getColumns(healthCheckRecords);
        return (
            <div>
                <div className="health-check-record-sticky table-box">
                    {/* <FormItem
                        colon={false}
                        className="health-check-record-add-row"
                        label="健康档案"
                    >
                        <Button className="health-check-record-add ant-btn-bordered" icon="plus" style={buttonStyle} onClick={this.addRecordClickListener}>
                            添加
                        </Button>
                    </FormItem> */}
                    <div className="textRight"><Button type="primary" onClick={this.addRecordClickListener}>录入健康档案</Button></div>
                    {dataSource ? <Table
                        dataSource={dataSource}
                        columns={columns}
                        pagination={{
                            showSizeChanger: true,
                            total: pageIndex !== 1 && pageTotal === pageSize ? pageTotal+1 : pageTotal,
                            showTotal: () => `第 ${pageIndex} 页`,
                            pageSizeOptions: ['10','20','50','100'],
                            current: pageIndex,
                            pageSize: pageSize,
                        }}
                        onChange={this.tableChange}
                    /> : null}
                    {/* <div style={{paddingLeft:"99px"}}>{this.state.dataSource.length>0?this.PGtable():null}</div> */}
                </div>
                {this.state.visible?<div>
                <Modal
                    title={this.state.getDetailData.physicalExaminationDate ? !this.state.editPower ? '查看健康档案':'编辑健康档案' : '录入健康档案'}
                    visible={this.state.visible}
                    // onOk={this.handleOk}
                    wrapClassName = "jkModal"
                    footer={null}
                    onCancel={this.handleCancel}
                    >
                        {this.state.getDetailData && this.state.visible?<div>
                        {/* <NewTable onRef={this.onRef} initMainData={this.initMainData.bind(this)} idCard={patientInfo.idCard} sex={patientInfo.sex} patientId={patientId} detailData={this.state.getDetailData} visible={this.state.visible}></NewTable> */}
                        <NewTable
                            // onRef={this.onRef}
                            ref="getIsSaveBtnClick"
                            initMainData={this.initMainData.bind(this)}
                                idCard={patientInfo.idCard} sex={patientInfo.sex} birthday={ patientInfo.birthday }
                            patientId={patientId}
                            editPower={this.state.editPower}
                            detailData={this.state.getDetailData}>
                        </NewTable>
                    </div>:null}
                </Modal>
                </div>:null}
            </div>
        );
    }
}
